package com.tim.app.ui.view;

import android.content.Context;
import android.os.Build;
import android.support.annotation.Nullable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.AppKey;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.ActionStateMsg;
import com.tim.app.server.entry.Problem;
import com.tim.app.server.entry.Topic;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.FollowResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.selected.InviteToAnswerActivity;
import com.tim.app.ui.activity.selected.QuestionAndAnswerDetailActivity;
import com.tim.app.ui.activity.selected.TopicDetailActivity;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import cn.carbs.android.expandabletextview.library.ExpandableTextView;

/**
 * 问答详情的header
 */

public class QuestionAndAnswerHeadView extends LinearLayout implements View.OnClickListener {

    private TextView tvTitle;
    private ExpandableTextView etvQuestion;
    private LSWebView lwvContent;
    private TextView tvFollowNumber;
    private TextView tvFollow;
    private TextView tvAnswerNumber;
    private TextView tvInviteToAnswer;
    private android.support.v7.widget.LinearLayoutCompat llSubject;

    public QuestionAndAnswerHeadView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        llSubject = (android.support.v7.widget.LinearLayoutCompat) findViewById(R.id.llSubject);
        etvQuestion = (ExpandableTextView) findViewById(R.id.etvQuestion);
        lwvContent = (LSWebView) findViewById(R.id.lwvContent);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvFollowNumber = (TextView) findViewById(R.id.tvFollowNumber);
        tvFollow = (TextView) findViewById(R.id.tvFollow);
        tvInviteToAnswer = (TextView) findViewById(R.id.tvInviteToAnswer);
        tvAnswerNumber = (TextView) findViewById(R.id.tvAnswerNumber);
        etvQuestion.setExpandListener(new ExpandableTextView.OnExpandListener() {
            @Override
            public void onExpand(ExpandableTextView expandableTextView) {
                etvQuestion.setVisibility(View.GONE);
                lwvContent.setVisibility(View.VISIBLE);
            }

            @Override
            public void onShrink(ExpandableTextView expandableTextView) {

            }
        });

        tvInviteToAnswer.setOnClickListener(this);
        tvFollow.setOnClickListener(this);
    }

    Problem problem;

    public void setData(final Problem problem) {
        if (null == problem)
            return;
        this.problem = problem;
        if (!TextUtils.isEmpty(problem.getTitle())) {
            tvTitle.setText(problem.getTitle());
        }
        if (!TextUtils.isEmpty(problem.getDigest().trim())) {
            etvQuestion.setText(problem.getDigest().replace("\n",""));

            this.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                public void onGlobalLayout() {
                    ViewTreeObserver obs = etvQuestion.getViewTreeObserver();
                    if (Build.VERSION.SDK_INT >= 16) {
                        obs.removeOnGlobalLayoutListener(this);
                    } else {
                        obs.removeGlobalOnLayoutListener(this);
                    }
                    TextPaint mTextPaint = etvQuestion.getPaint();
                    int mTextViewWidth = (int) mTextPaint.measureText(problem.getDigest().replace("\n",""));
                    if (mTextViewWidth <= etvQuestion.getWidth() * 2) {
                        etvQuestion.setVisibility(View.GONE);
                        lwvContent.setVisibility(View.VISIBLE);
                    } else {
                    }
                }
            });
        } else {
            etvQuestion.setVisibility(View.GONE);
            lwvContent.setVisibility(View.VISIBLE);
        }
        tvFollowNumber.setText(getContext().getString(R.string.prbolemFollowCount, String.valueOf(problem.getConcernCount())));
        tvAnswerNumber.setText(getContext().getString(R.string.prbolemAnswerCount, String.valueOf(problem.getAnswerCount())));
        if (null != problem.getTopicList()) {
            if (llSubject.getChildCount() > 0) {
                llSubject.removeAllViews();
            }
            for (int i = 0; i < problem.getTopicList().size(); i++) {
                final Topic subject = problem.getTopicList().get(i);
                TextView textView = new TextView(getContext());
                textView.setText(subject.getTopicName());
                textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 11);
                textView.setBackground(getResources().getDrawable(R.drawable.bg_shape_gray_round));
                textView.setTextColor(getResources().getColor(R.color.text_desc_color));
                textView.setPadding((int) RT.getDensity() * 11, (int) RT.getDensity() * 1, (int) RT.getDensity() * 9, (int) RT.getDensity() * 1);
                textView.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        TopicDetailActivity.start(getContext(), subject, false);
                    }
                });
                llSubject.addView(textView);
            }
        }

        if (null != problem.getActionStateMsg()) {
            if (null != problem.getActionStateMsg().getContentState()) {
                tvFollow.setSelected(true);
                tvFollow.setText("已关注问题");
            } else {
                tvFollow.setSelected(false);
                tvFollow.setText("关注问题");
            }
        }

    }

    public void updateAnswerCount(final Problem problem) {
        if (null == problem)
            return;
        this.problem = problem;
        tvAnswerNumber.setText(getContext().getString(R.string.prbolemAnswerCount, String.valueOf(problem.getAnswerCount())));
    }

    public void setContentUrl(String url) {
        lwvContent.openUrl(url);
    }

    /**
     * 刷新回答数量
     *
     * @param answerCount
     */
    public void refreshAnswerCount(int answerCount) {
        tvAnswerNumber.setText(getContext().getString(R.string.tvTotalAnswerNumber, String.valueOf(answerCount)));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvFollow:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(getContext());
                    return;
                }
                followOrCancelFollow();
                break;
            case R.id.tvInviteToAnswer:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(getContext());
                    return;
                }
                InviteToAnswerActivity.start(getContext(), problem.getId());
                break;
        }
    }

    /**
     * 关注/取消关注
     */
    private void followOrCancelFollow() {
        tvFollow.setEnabled(false);
        if (null != problem.getActionStateMsg() && problem.getActionStateMsg().getContentState() != null) {
            int id = problem.getActionStateMsg().getContentState();
            API_User.ins().cancelFollow(QuestionAndAnswerDetailActivity.TAG, id, UserManager.ins().getUserId(), problem.getId(), AppKey.TYPE_PROBLEM, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    tvFollow.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        problem.setConcernCount(problem.getConcernCount() - 1);
                        tvFollowNumber.setText(getContext().getString(R.string.prbolemFollowCount, String.valueOf(problem.getConcernCount())));
                        problem.getActionStateMsg().setContentState(null);
                        tvFollow.setSelected(false);
                        tvFollow.setText("关注问题");
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        } else {
            API_User.ins().addFollow(QuestionAndAnswerDetailActivity.TAG, UserManager.ins().getUserId(), problem.getId(), AppKey.TYPE_PROBLEM, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    tvFollow.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        FollowResult result = new Gson().fromJson(resultValue, FollowResult.class);
                        if (null != result && null != result.getRes()) {
                            if (problem.getActionStateMsg() == null) {
                                problem.setActionStateMsg(new ActionStateMsg());
                            }
                            problem.getActionStateMsg().setContentState(result.getRes().getConcern().getId());
                            problem.setConcernCount(problem.getConcernCount() + 1);
                            tvFollowNumber.setText(getContext().getString(R.string.prbolemFollowCount, String.valueOf(problem.getConcernCount())));
                            tvFollow.setSelected(true);
                            tvFollow.setText("已关注问题");
                        }
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        }
    }

}
